package com.harmony.pilot.agent.service;

import com.harmony.pilot.agent.model.Conversation;
import com.harmony.pilot.agent.model.ConversationContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class ConversationManager {
    
    private final RedisTemplate<String, Conversation> conversationRedisTemplate;
    private final ConcurrentHashMap<String, Conversation> memoryCache;
    
    private static final String REDIS_KEY_PREFIX = "agent:conversation:";
    private static final Duration CONVERSATION_TTL = Duration.ofHours(24);
    
    public ConversationManager(RedisTemplate<String, Conversation> conversationRedisTemplate) {
        this.conversationRedisTemplate = conversationRedisTemplate;
        this.memoryCache = new ConcurrentHashMap<>();
    }
    
    public Conversation getConversation(String sessionId) {
        // 先查内存缓存
        Conversation conversation = memoryCache.get(sessionId);
        if (conversation != null) {
            return conversation;
        }
        
        // 再查Redis
        conversation = conversationRedisTemplate.opsForValue().get(REDIS_KEY_PREFIX + sessionId);
        if (conversation != null) {
            memoryCache.put(sessionId, conversation);
            return conversation;
        }
        
        // 创建新对话
        conversation = new Conversation(sessionId);
        saveConversation(conversation);
        return conversation;
    }
    
    public void saveConversation(Conversation conversation) {
        memoryCache.put(conversation.getSessionId(), conversation);
        conversationRedisTemplate.opsForValue().set(
            REDIS_KEY_PREFIX + conversation.getSessionId(),
            conversation,
            CONVERSATION_TTL
        );
    }
    
    public void updateContext(String sessionId, ConversationContext context) {
        Conversation conversation = getConversation(sessionId);
        conversation.setContext(context);
        saveConversation(conversation);
    }
    
    public void clearConversation(String sessionId) {
        memoryCache.remove(sessionId);
        conversationRedisTemplate.delete(REDIS_KEY_PREFIX + sessionId);
    }
}

